package test

import (
	"bookkeeping-gin/app/common/request"
	"bookkeeping-gin/app/common/response"
	"bookkeeping-gin/bootstrap"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"net/http/httptest"
)

func InitConfig() {
	// init config
	bootstrap.InitConfig()

	// init log
	bootstrap.InitLog()

	// init db
	bootstrap.InitDB()

	// init validator
	bootstrap.InitValidator()

	// init redis
	bootstrap.InitRedis()
}

func getAccessToken() (token string, r *gin.Engine) {
	InitConfig()
	r = bootstrap.SetUpRouter()

	w := httptest.NewRecorder()
	user := request.RegisterFormWithPwd{
		Username: "testuser",
		Password: "testpassword",
	}

	// 创建一个JSON格式的请求体
	jsonUser, err := json.Marshal(user)
	if err != nil {
		log.Fatalln(err)
	}
	req := httptest.NewRequest(http.MethodPost, "/api/v1/user/login", bytes.NewBuffer(jsonUser))
	r.ServeHTTP(w, req)
	// 将响应体转换为结构体
	var resp response.Response
	err = json.Unmarshal(w.Body.Bytes(), &resp)
	if err != nil {
		log.Fatalf("unmarshal response failed: %s\n", err)
	}
	tokenData, ok := resp.Data.(map[string]any)
	if !ok {
		log.Fatalln("unmarshal resp.Data failed")
	}
	fmt.Printf("%+v\n", resp)
	token, ok = tokenData["access_token"].(string)
	if !ok {
		log.Fatalln("unmarshal tokenData failed")
	}
	return
}
